
#include "../../common/dispatcher.hpp"
#include "../../client/requestor.hpp"
#include "../../client/rpc_caller.hpp"

#include <thread>

void callback(const Json::Value& result)
{
    ILOG("callback result: %d",result.asInt());
}

int main()
{
    auto requestor = std::make_shared<gmrpc::client::Requestor>();
    auto caller = std::make_shared<gmrpc::client::RpcCaller>(requestor);

    auto dispatcher = std::make_shared<gmrpc::Dispatcher>();
    auto rsp_cb = std::bind(&gmrpc::client::Requestor::onResponse, requestor.get(),
                            std::placeholders::_1, std::placeholders::_2);

    dispatcher->registerHandler<gmrpc::BaseMessage>(gmrpc::MType::RSP_RPC, rsp_cb); // 注册映射关系

    auto message_cb = std::bind(&gmrpc::Dispatcher::onMessage, dispatcher.get(),
                                std::placeholders::_1, std::placeholders::_2);

    auto client = gmrpc::ClientFactory::create("127.0.0.1", 9090);
    client->setMessageCallback(message_cb);
    client->connect();

    auto conn = client->connection();
    Json::Value params, result;
    params["num1"] = 11;
    params["num2"] = 22;
    bool ret = caller->call(conn, "Add", params, result);
    if (ret != false)
    {
        std::cout << "result: " << result.asInt() << std::endl;
    }

    gmrpc::client::RpcCaller::JsonAsyncResponse res_future;

    params["num1"] = 33;
    params["num2"] = 44;
    ret = caller->call(conn, "Add", params, res_future);
    if (ret != false)
    {
        result = res_future.get();
        std::cout << "result: " << result.asInt() << std::endl;
    }

    params["num1"] = 55;
    params["num2"] = 66;
    ret = caller->call(conn, "Add", params, callback);
    DLOG("------------\n");
    std::this_thread::sleep_for(std::chrono::seconds(1));
    client->shutdown();
    return 0;
}